package com.shxy.rlzy.service.impl;

import com.shxy.rlzy.entity.*;
import com.shxy.rlzy.mapper.*;
import com.shxy.rlzy.service.IEmployeeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeUserService implements IEmployeeUserService {
    @Autowired
    private EmployeeInfoMapper employeeInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private DepartMapper departMapper;
    private String avatarUrl = "https://image-1300566513.cos.ap-guangzhou.myqcloud.com/upload/images/5a9f48118166308daba8b6da7e466aab.jpg";

    @Override
    public boolean importClerk(Long clerkId) {
        // 1、将员工信息导入用户表
        User user = importFromEmployee(clerkId);
        // 2、获取工资员信息
        Role role = roleMapper.getByCode("clerk");
        if(role == null) return false;

        // 3、将员工设置为工资员
        UserRole userRole = userRoleMapper.getByUserId(user.getId());
        if(userRole == null) {
            userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(role.getId());
            if(userRoleMapper.insert(userRole) <= 0) {
                return false;
            }
        }
        else {
            userRole.setRoleId(role.getId());
            if(userRoleMapper.updateById(userRole) <= 0) {
                return false;
            }
        }

        return true;
    }

    @Override
    public User importFromEmployee(Long employeeId) {
        EmployeeInfo emp = employeeInfoMapper.selectById(employeeId);
        User user = userMapper.getByUserName(emp.getPhone());
        if(user == null){
            user = new User();
            user.setUsername(emp.getPhone());
            user.setPhone(emp.getPhone());
            user.setPassword("123456");
            user.setAvatar(avatarUrl);
            if(userMapper.insert(user) > 0){
                return userMapper.getByUserName(user.getUsername());
            }
        }
        return user;
    }

    @Override
    public void refreshClerks() {
        // 获取所有工资员编号
        List<Long> clerkIds = departMapper.getAll().stream().filter(depart -> depart.getClerkId() != null).map(Depart::getClerkId).toList();
        clerkIds.forEach(id -> {
            importClerk(id);
        });
    }
}
